home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlipc.Z / perlipc
Encoding:
Text File  |  1998-10-28  |  69.8 KB  |  1,981 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlipc - Perl interprocess communication (signals, fifos,
  10.       pipes, safe subprocesses, sockets, and semaphores)
  11.  
  12.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  13.       The basic IPC    facilities of Perl are built out of the    good
  14.       old Unix signals, named pipes, pipe opens, the Berkeley
  15.       socket routines, and SysV IPC    calls.    Each is    used in
  16.       slightly different situations.
  17.  
  18.      SSSSiiiiggggnnnnaaaallllssss
  19.       Perl uses a simple signal handling model: the    %SIG hash
  20.       contains names or references of user-installed signal
  21.       handlers.  These handlers will be called with    an argument
  22.       which    is the name of the signal that triggered it.  A    signal
  23.       may be generated intentionally from a    particular keyboard
  24.       sequence like    control-C or control-Z,    sent to    you from
  25.       another process, or triggered    automatically by the kernel
  26.       when special events transpire, like a    child process exiting,
  27.       your process running out of stack space, or hitting file
  28.       size limit.
  29.  
  30.       For example, to trap an interrupt signal, set    up a handler
  31.       like this.  Do as little as you possibly can in your
  32.       handler; notice how all we do    is set a global    variable and
  33.       then raise an    exception.  That's because on most systems,
  34.       libraries are    not re-entrant;    particularly, memory
  35.       allocation and I/O routines are not.    That means that    doing
  36.       nearly _a_n_y_t_h_i_n_g in your handler could    in theory trigger a
  37.       memory fault and subsequent core dump.
  38.  
  39.           sub catch_zap {
  40.           my $signame =    shift;
  41.           $shucks++;
  42.           die "Somebody    sent me    a SIG$signame";
  43.           }
  44.           $SIG{INT}    = 'catch_zap';    # could    fail in    modules
  45.           $SIG{INT}    = \&catch_zap;    # best strategy
  46.  
  47.       The names of the signals are the ones    listed out by kill -l
  48.       on your system, or you can retrieve them from    the Config
  49.       module.  Set up an @signame list indexed by number to    get
  50.       the name and a %signo    table indexed by name to get the
  51.       number:
  52.  
  53.           use Config;
  54.           defined $Config{sig_name}    || die "No sigs?";
  55.           foreach $name (split(' ',    $Config{sig_name})) {
  56.           $signo{$name}    = $i;
  57.           $signame[$i] = $name;
  58.           $i++;
  59.           }
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  71.  
  72.  
  73.  
  74.       So to    check whether signal 17    and SIGALRM were the same, do
  75.       just this:
  76.  
  77.           print "signal #17    = $signame[17]\n";
  78.           if ($signo{ALRM})    {
  79.           print    "SIGALRM is $signo{ALRM}\n";
  80.           }
  81.  
  82.       You may also choose to assign    the strings 'IGNORE' or
  83.       'DEFAULT' as the handler, in which case Perl will try    to
  84.       discard the signal or    do the default thing.  Some signals
  85.       can be neither trapped nor ignored, such as the KILL and
  86.       STOP (but not    the TSTP) signals.  One    strategy for
  87.       temporarily ignoring signals is to use a _l_o_c_a_l() statement,
  88.       which    will be    automatically restored once your block is
  89.       exited.  (Remember that _l_o_c_a_l() values are "inherited" by
  90.       functions called from    within that block.)
  91.  
  92.           sub precious {
  93.           local    $SIG{INT} = 'IGNORE';
  94.           &more_functions;
  95.           }
  96.           sub more_functions {
  97.           # interrupts still ignored, for now...
  98.           }
  99.  
  100.       Sending a signal to a    negative process ID means that you
  101.       send the signal to the entire    Unix process-group.  This code
  102.       sends    a hang-up signal to all    processes in the current
  103.       process group    (and sets $SIG{HUP} to IGNORE so it doesn't
  104.       kill itself):
  105.  
  106.           {
  107.           local    $SIG{HUP} = 'IGNORE';
  108.           kill HUP => -$$;
  109.           # snazzy writing of: kill('HUP', -$$)
  110.           }
  111.  
  112.       Another interesting signal to    send is    signal number zero.
  113.       This doesn't actually    affect another process,    but instead
  114.       checks whether it's alive or has changed its UID.
  115.  
  116.           unless (kill 0 =>    $kid_pid) {
  117.           warn "something wicked happened to $kid_pid";
  118.           }
  119.  
  120.       You might also want to employ    anonymous functions for    simple
  121.       signal handlers:
  122.  
  123.           $SIG{INT}    = sub {    die "\nOutta here!\n" };
  124.  
  125.       But that will    be problematic for the more complicated
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  137.  
  138.  
  139.  
  140.       handlers that    need to    reinstall themselves.  Because Perl's
  141.       signal mechanism is currently    based on the _s_i_g_n_a_l(3)
  142.       function from    the C library, you may sometimes be so
  143.       misfortunate as to run on systems where that function    is
  144.       "broken", that is, it    behaves    in the old unreliable SysV way
  145.       rather than the newer, more reasonable BSD and POSIX
  146.       fashion.  So you'll see defensive people writing signal
  147.       handlers like    this:
  148.  
  149.           sub REAPER {
  150.           $waitedpid = wait;
  151.           # loathe sysV: it makes us not only reinstate
  152.           # the    handler, but place it after the    wait
  153.           $SIG{CHLD} = \&REAPER;
  154.           }
  155.           $SIG{CHLD} = \&REAPER;
  156.           #    now do something that forks...
  157.  
  158.       or even the more elaborate:
  159.  
  160.           use POSIX    ":sys_wait_h";
  161.           sub REAPER {
  162.           my $child;
  163.           while    ($child    = waitpid(-1,WNOHANG)) {
  164.               $Kid_Status{$child} = $?;
  165.           }
  166.           $SIG{CHLD} = \&REAPER;  # still loathe sysV
  167.           }
  168.           $SIG{CHLD} = \&REAPER;
  169.           #    do something that forks...
  170.  
  171.       Signal handling is also used for timeouts in Unix,   While
  172.       safely protected within an eval{} block, you set a signal
  173.       handler to trap alarm    signals    and then schedule to have one
  174.       delivered to you in some number of seconds.  Then try    your
  175.       blocking operation, clearing the alarm when it's done    but
  176.       not before you've exited your    eval{} block.  If it goes off,
  177.       you'll use _d_i_e() to jump out of the block, much as you might
  178.       using    _l_o_n_g_j_m_p() or _t_h_r_o_w() in    other languages.
  179.  
  180.       Here's an example:
  181.  
  182.           eval {
  183.           local    $SIG{ALRM} = sub { die "alarm clock restart" };
  184.           alarm    10;
  185.           flock(FH, 2);      # blocking write lock
  186.           alarm    0;
  187.           };
  188.           if ($@ and $@ !~ /alarm clock restart/) {    die }
  189.  
  190.       For more complex signal handling, you    might see the standard
  191.       POSIX    module.     Lamentably, this is almost entirely
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  203.  
  204.  
  205.  
  206.       undocumented,    but the    _t/_l_i_b/_p_o_s_i_x._t file from    the Perl
  207.       source distribution has some examples    in it.
  208.  
  209.      NNNNaaaammmmeeeedddd PPPPiiiippppeeeessss
  210.       A named pipe (often referred to as a FIFO) is    an old Unix
  211.       IPC mechanism    for processes communicating on the same
  212.       machine.  It works just like a regular, connected anonymous
  213.       pipes, except    that the processes rendezvous using a filename
  214.       and don't have to be related.
  215.  
  216.       To create a named pipe, use the Unix command _m_k_n_o_d(1)    or on
  217.       some systems,    _m_k_f_i_f_o(1).  These may not be in    your normal
  218.       path.
  219.  
  220.           #    system return val is backwards,    so && not ||
  221.           #
  222.           $ENV{PATH} .= ":/etc:/usr/etc";
  223.           if  (     system('mknod',  $path, 'p')
  224.               && system('mkfifo', $path) )
  225.           {
  226.           die "mk{nod,fifo} $path failed";
  227.           }
  228.  
  229.       A fifo is convenient when you    want to    connect    a process to
  230.       an unrelated one.  When you open a fifo, the program will
  231.       block    until there's something    on the other end.
  232.  
  233.       For example, let's say you'd like to have your ._s_i_g_n_a_t_u_r_e
  234.       file be a named pipe that has    a Perl program on the other
  235.       end.    Now every time any program (like a mailer, news
  236.       reader, finger program, etc.)    tries to read from that    file,
  237.       the reading program will block and your program will supply
  238.       the new signature.  We'll use    the pipe-checking file test ----pppp
  239.       to find out whether anyone (or anything) has accidentally
  240.       removed our fifo.
  241.  
  242.           chdir; # go home
  243.           $FIFO = '.signature';
  244.           $ENV{PATH} .= ":/etc:/usr/games";
  245.  
  246.           while (1)    {
  247.           unless (-p $FIFO) {
  248.               unlink $FIFO;
  249.               system('mknod', $FIFO, 'p')
  250.               && die "can't    mknod $FIFO: $!";
  251.           }
  252.  
  253.  
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  269.  
  270.  
  271.  
  272.           # next line blocks until there's a reader
  273.           open (FIFO, "> $FIFO") || die    "can't write $FIFO: $!";
  274.           print    FIFO "John Smith (smith\@host.org)\n", `fortune    -s`;
  275.           close    FIFO;
  276.           sleep    2;    #    to avoid dup signals
  277.           }
  278.  
  279.  
  280.       WWWWAAAARRRRNNNNIIIINNNNGGGG
  281.  
  282.       By installing    Perl code to deal with signals,    you're
  283.       exposing yourself to danger from two things.    First, few
  284.       system library functions are re-entrant.  If the signal
  285.       interrupts while Perl    is executing one function (like
  286.       _m_a_l_l_o_c(3) or _p_r_i_n_t_f(3)), and your signal handler then    calls
  287.       the same function again, you could get unpredictable
  288.       behavior--often, a core dump.     Second, Perl isn't itself
  289.       re-entrant at    the lowest levels.  If the signal interrupts
  290.       Perl while Perl is changing its own internal data
  291.       structures, similarly    unpredictable behaviour    may result.
  292.  
  293.       There    are two    things you can do, knowing this: be paranoid
  294.       or be    pragmatic.  The    paranoid approach is to    do as little
  295.       as possible in your signal handler.  Set an existing integer
  296.       variable that    already    has a value, and return.  This doesn't
  297.       help you if you're in    a slow system call, which will just
  298.       restart.  That means you have    to die to _l_o_n_g_j_u_m_p(3) out of
  299.       the handler.    Even this is a little cavalier for the true
  300.       paranoiac, who avoids    die in a handler because the system _i_s
  301.       out to get you.  The pragmatic approach is to    say ``I    know
  302.       the risks, but prefer    the convenience'', and to do anything
  303.       you want in your signal handler, prepared to clean up    core
  304.       dumps    now and    again.
  305.  
  306.       To forbid signal handlers altogether would bars you from
  307.       many interesting programs, including virtually everything in
  308.       this manpage,    since you could    no longer even write SIGCHLD
  309.       handlers.  Their dodginess is    expected to be addresses in
  310.       the 5.005 release.
  311.  
  312.      UUUUssssiiiinnnngggg _o_p_e_n(((()))) ffffoooorrrr IIIIPPPPCCCC
  313.       Perl's basic _o_p_e_n() statement    can also be used for
  314.       unidirectional interprocess communication by either
  315.       appending or prepending a pipe symbol    to the second argument
  316.       to _o_p_e_n().  Here's how to start something up in a child
  317.       process you intend to    write to:
  318.  
  319.           open(SPOOLER, "| cat -v |    lpr -h 2>/dev/null")
  320.                   || die "can't fork: $!";
  321.           local $SIG{PIPE} = sub { die "spooler pipe broke"    };
  322.           print SPOOLER "stuff\n";
  323.           close SPOOLER || die "bad    spool: $! $?";
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  335.  
  336.  
  337.  
  338.       And here's how to start up a child process you intend    to
  339.       read from:
  340.  
  341.           open(STATUS, "netstat -an    2>&1 |")
  342.                   || die "can't fork: $!";
  343.           while (<STATUS>) {
  344.           next if /^(tcp|udp)/;
  345.           print;
  346.           }
  347.           close STATUS || die "bad netstat:    $! $?";
  348.  
  349.       If one can be    sure that a particular program is a Perl
  350.       script that is expecting filenames in    @ARGV, the clever
  351.       programmer can write something like this:
  352.  
  353.           %    program    f1 "cmd1|" - f2    "cmd2|"    f3 < tmpfile
  354.  
  355.       and irrespective of which shell it's called from, the    Perl
  356.       program will read from the file _f_1, the process _c_m_d_1,
  357.       standard input (_t_m_p_f_i_l_e in this case), the _f_2    file, the _c_m_d_2
  358.       command, and finally the _f_3 file.  Pretty nifty, eh?
  359.  
  360.       You might notice that    you could use backticks    for much the
  361.       same effect as opening a pipe    for reading:
  362.  
  363.           print grep { !/^(tcp|udp)/ } `netstat -an    2>&1`;
  364.           die "bad netstat"    if $?;
  365.  
  366.       While    this is    true on    the surface, it's much more efficient
  367.       to process the file one line or record at a time because
  368.       then you don't have to read the whole    thing into memory at
  369.       once.    It also    gives you finer    control    of the whole process,
  370.       letting you to kill off the child process early if you'd
  371.       like.
  372.  
  373.       Be careful to    check both the _o_p_e_n() and the _c_l_o_s_e() return
  374.       values.  If you're _w_r_i_t_i_n_g to    a pipe,    you should also    trap
  375.       SIGPIPE.  Otherwise, think of    what happens when you start up
  376.       a pipe to a command that doesn't exist: the _o_p_e_n() will in
  377.       all likelihood succeed (it only reflects the _f_o_r_k()'s
  378.       success), but    then your output will fail--spectacularly.
  379.       Perl can't know whether the command worked because your
  380.       command is actually running in a separate process whose
  381.       _e_x_e_c() might have failed.  Therefore,    while readers of bogus
  382.       commands return just a quick end of file, writers to bogus
  383.       command will trigger a signal    they'd better be prepared to
  384.       handle.  Consider:
  385.  
  386.           open(FH, "|bogus")  or die "can't    fork: $!";
  387.           print FH "bang\n"      or die "can't    write: $!";
  388.           close FH          or die "can't    close: $!";
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  401.  
  402.  
  403.  
  404.       That won't blow up until the close, and it will blow up with
  405.       a SIGPIPE.  To catch it, you could use this:
  406.  
  407.           $SIG{PIPE} = 'IGNORE';
  408.           open(FH, "|bogus")  or die "can't    fork: $!";
  409.           print FH "bang\n"      or die "can't    write: $!";
  410.           close FH          or die "can't    close: status=$?";
  411.  
  412.  
  413.       FFFFiiiilllleeeehhhhaaaannnnddddlllleeeessss
  414.  
  415.       Both the main    process    and any    child processes    it forks share
  416.       the same STDIN, STDOUT, and STDERR filehandles.  If both
  417.       processes try    to access them at once,    strange    things can
  418.       happen.  You'll certainly want to any    stdio flush output
  419.       buffers before forking.  You may also    want to    close or
  420.       reopen the filehandles for the child.     You can get around
  421.       this by opening your pipe with _o_p_e_n(), but on    some systems
  422.       this means that the child process cannot outlive the parent.
  423.  
  424.       BBBBaaaacccckkkkggggrrrroooouuuunnnndddd PPPPrrrroooocccceeeesssssssseeeessss
  425.  
  426.       You can run a    command    in the background with:
  427.  
  428.           system("cmd &");
  429.  
  430.       The command's    STDOUT and STDERR (and possibly    STDIN,
  431.       depending on your shell) will    be the same as the parent's.
  432.       You won't need to catch SIGCHLD because of the double-fork
  433.       taking place (see below for more details).
  434.  
  435.       CCCCoooommmmpppplllleeeetttteeee DDDDiiiissssssssoooocccciiiiaaaattttiiiioooonnnn    ooooffff CCCChhhhiiiilllldddd ffffrrrroooommmm PPPPaaaarrrreeeennnntttt
  436.  
  437.       In some cases    (starting server processes, for    instance)
  438.       you'll want to complete dissociate the child process from
  439.       the parent.     The easiest way is to use:
  440.  
  441.           use POSIX    qw(setsid);
  442.           setsid()          or die "Can't    start a    new session: $!";
  443.  
  444.       However, you may not be on POSIX.  The following process is
  445.       reported to work on most Unixish systems.  Non-Unix users
  446.       should check their Your_OS::Process module for other
  447.       solutions.
  448.  
  449.       +o   Open /dev/tty and    use the    TIOCNOTTY ioctl    on it.    See
  450.           the _t_t_y(_4) manpage for details.
  451.  
  452.       +o   Change directory to /
  453.  
  454.       +o   Reopen STDIN, STDOUT, and    STDERR so they're not
  455.           connected    to the old tty.
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  467.  
  468.  
  469.  
  470.       +o   Background yourself like this:
  471.  
  472.           fork && exit;
  473.  
  474.  
  475.       +o   Ignore hangup signals in case you're running on a    shell
  476.           that doesn't automatically no-hup    you:
  477.  
  478.           $SIG{HUP} = 'IGNORE';          #    or whatever you'd like
  479.  
  480.  
  481.       SSSSaaaaffffeeee PPPPiiiippppeeee OOOOppppeeeennnnssss
  482.  
  483.       Another interesting approach to IPC is making    your single
  484.       program go multiprocess and communicate between (or even
  485.       amongst) yourselves.    The _o_p_e_n() function will accept    a file
  486.       argument of either "-|" or "|-" to do    a very interesting
  487.       thing: it forks a child connected to the filehandle you've
  488.       opened.  The child is    running    the same program as the
  489.       parent.  This    is useful for safely opening a file when
  490.       running under    an assumed UID or GID, for example.  If    you
  491.       open a pipe _t_o minus,    you can    write to the filehandle    you
  492.       opened and your kid will find    it in his STDIN.  If you open
  493.       a pipe _f_r_o_m minus, you can read from the filehandle you
  494.       opened whatever your kid writes to his STDOUT.
  495.  
  496.           use English;
  497.           my $sleep_count =    0;
  498.  
  499.           do {
  500.           $pid = open(KID_TO_WRITE, "|-");
  501.           unless (defined $pid)    {
  502.               warn "cannot fork: $!";
  503.               die "bailing out"    if $sleep_count++ > 6;
  504.               sleep 10;
  505.           }
  506.           }    until defined $pid;
  507.  
  508.           if ($pid)    {  # parent
  509.           print    KID_TO_WRITE @some_data;
  510.           close(KID_TO_WRITE) || warn "kid exited $?";
  511.           }    else {       # child
  512.           ($EUID, $EGID) = ($UID, $GID); # suid    progs only
  513.           open (FILE, "> /safe/file")
  514.               || die "can't open /safe/file: $!";
  515.           while    (<STDIN>) {
  516.               print FILE; # child's STDIN is parent's KID
  517.           }
  518.           exit;     # don't forget    this
  519.           }
  520.  
  521.       Another common use for this construct    is when    you need to
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  533.  
  534.  
  535.  
  536.       execute something without the    shell's    interference.  With
  537.       _s_y_s_t_e_m(), it's straightforward, but you can't    use a pipe
  538.       open or backticks safely.  That's because there's no way to
  539.       stop the shell from getting its hands    on your    arguments.
  540.       Instead, use lower-level control to call _e_x_e_c() directly.
  541.  
  542.       Here's a safe    backtick or pipe open for read:
  543.  
  544.           #    add error processing as    above
  545.           $pid = open(KID_TO_READ, "-|");
  546.  
  547.           if ($pid)    {   # parent
  548.           while    (<KID_TO_READ>)    {
  549.               #    do something interesting
  550.           }
  551.           close(KID_TO_READ) ||    warn "kid exited $?";
  552.  
  553.           }    else {        # child
  554.           ($EUID, $EGID) = ($UID, $GID); # suid    only
  555.           exec($program, @options, @args)
  556.               || die "can't exec program: $!";
  557.           # NOTREACHED
  558.           }
  559.  
  560.       And here's a safe pipe open for writing:
  561.  
  562.           #    add error processing as    above
  563.           $pid = open(KID_TO_WRITE,    "|-");
  564.           $SIG{ALRM} = sub { die "whoops, $program pipe broke" };
  565.  
  566.           if ($pid)    {  # parent
  567.           for (@data) {
  568.               print KID_TO_WRITE;
  569.           }
  570.           close(KID_TO_WRITE) || warn "kid exited $?";
  571.  
  572.           }    else {       # child
  573.           ($EUID, $EGID) = ($UID, $GID);
  574.           exec($program, @options, @args)
  575.               || die "can't exec program: $!";
  576.           # NOTREACHED
  577.           }
  578.  
  579.       Note that these operations are full Unix forks, which    means
  580.       they may not be correctly implemented    on alien systems.
  581.       Additionally,    these are not true multithreading.  If you'd
  582.       like to learn    more about threading, see the _m_o_d_u_l_e_s file
  583.       mentioned below in the SEE ALSO section.
  584.  
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  599.  
  600.  
  601.  
  602.       BBBBiiiiddddiiiirrrreeeeccccttttiiiioooonnnnaaaallll    CCCCoooommmmmmmmuuuunnnniiiiccccaaaattttiiiioooonnnn wwwwiiiitttthhhh AAAAnnnnooootttthhhheeeerrrr PPPPrrrroooocccceeeessssssss
  603.  
  604.       While    this works reasonably well for unidirectional
  605.       communication, what about bidirectional communication?  The
  606.       obvious thing    you'd like to do doesn't actually work:
  607.  
  608.           open(PROG_FOR_READING_AND_WRITING, "| some program |")
  609.  
  610.       and if you forget to use the ----wwww flag,    then you'll miss out
  611.       entirely on the diagnostic message:
  612.  
  613.           Can't do bidirectional pipe at -e    line 1.
  614.  
  615.       If you really    want to, you can use the standard _o_p_e_n_2()
  616.       library function to catch both ends.    There's    also an
  617.       _o_p_e_n_3() for tridirectional I/O so you    can also catch your
  618.       child's STDERR, but doing so would then require an awkward
  619.       _s_e_l_e_c_t() loop    and wouldn't allow you to use normal Perl
  620.       input    operations.
  621.  
  622.       If you look at its source, you'll see    that _o_p_e_n_2() uses
  623.       low-level primitives like Unix _p_i_p_e()    and _e_x_e_c() calls to
  624.       create all the connections.  While it    might have been
  625.       slightly more    efficient by using _s_o_c_k_e_t_p_a_i_r(), it would have
  626.       then been even less portable than it already is.  The
  627.       _o_p_e_n_2() and _o_p_e_n_3() functions    are  unlikely to work anywhere
  628.       except on a Unix system or some other    one purporting to be
  629.       POSIX    compliant.
  630.  
  631.       Here's an example of using _o_p_e_n_2():
  632.  
  633.           use FileHandle;
  634.           use IPC::Open2;
  635.           $pid = open2(*Reader, *Writer, "cat -u -n" );
  636.           Writer->autoflush(); # default here, actually
  637.           print Writer "stuff\n";
  638.           $got = <Reader>;
  639.  
  640.       The problem with this    is that    Unix buffering is really going
  641.       to ruin your day.  Even though your Writer filehandle    is
  642.       auto-flushed,    and the    process    on the other end will get your
  643.       data in a timely manner, you can't usually do    anything to
  644.       force    it to give it back to you in a similarly quick
  645.       fashion.  In this case, we could, because we gave _c_a_t    a ----uuuu
  646.       flag to make it unbuffered.  But very    few Unix commands are
  647.       designed to operate over pipes, so this seldom works unless
  648.       you yourself wrote the program on the    other end of the
  649.       double-ended pipe.
  650.  
  651.       A solution to    this is    the nonstandard    _C_o_m_m._p_l    library.  It
  652.       uses pseudo-ttys to make your    program    behave more
  653.       reasonably:
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  665.  
  666.  
  667.  
  668.           require 'Comm.pl';
  669.           $ph = open_proc('cat -n');
  670.           for (1..10) {
  671.           print    $ph "a line\n";
  672.           print    "got back ", scalar <$ph>;
  673.           }
  674.  
  675.       This way you don't have to have control over the source code
  676.       of the program you're    using.    The _C_o_m_m library also has
  677.       _e_x_p_e_c_t() and _i_n_t_e_r_a_c_t() functions.  Find the library (and we
  678.       hope its successor _I_P_C::_C_h_a_t)    at your    nearest    CPAN archive
  679.       as detailed in the SEE ALSO section below.
  680.  
  681.       The newer Expect.pm module from CPAN also addresses this
  682.       kind of thing.  This module requires two other modules from
  683.       CPAN:    IO::Pty    and IO::Stty.  It sets up a pseudo-terminal to
  684.       interact with    programs that insist on    using talking to the
  685.       terminal device driver.  If your system is amongst those
  686.       supported, this may be your best bet.
  687.  
  688.       BBBBiiiiddddiiiirrrreeeeccccttttiiiioooonnnnaaaallll    CCCCoooommmmmmmmuuuunnnniiiiccccaaaattttiiiioooonnnn wwwwiiiitttthhhh YYYYoooouuuurrrrsssseeeellllffff
  689.  
  690.       If you want, you may make low-level _p_i_p_e() and _f_o_r_k()    to
  691.       stitch this together by hand.     This example only talks to
  692.       itself, but you could    reopen the appropriate handles to
  693.       STDIN    and STDOUT and call other processes.
  694.  
  695.           #!/usr/bin/perl -w
  696.           #    pipe1 -    bidirectional communication using two pipe pairs
  697.           #        designed for the socketpair-challenged
  698.           use IO::Handle;      # thousands of lines just for    autoflush :-(
  699.           pipe(PARENT_RDR, CHILD_WTR);          # XXX: failure?
  700.           pipe(CHILD_RDR,  PARENT_WTR);          # XXX: failure?
  701.           CHILD_WTR->autoflush(1);
  702.           PARENT_WTR->autoflush(1);
  703.  
  704.           if ($pid = fork) {
  705.           close    PARENT_RDR; close PARENT_WTR;
  706.           print    CHILD_WTR "Parent Pid $$ is sending this\n";
  707.           chomp($line =    <CHILD_RDR>);
  708.           print    "Parent    Pid $$ just read this: `$line'\n";
  709.           close    CHILD_RDR; close CHILD_WTR;
  710.           waitpid($pid,0);
  711.           }    else {
  712.           die "cannot fork: $!"    unless defined $pid;
  713.           close    CHILD_RDR; close CHILD_WTR;
  714.           chomp($line =    <PARENT_RDR>);
  715.           print    "Child Pid $$ just read    this: `$line'\n";
  716.           print    PARENT_WTR "Child Pid $$ is sending this\n";
  717.           close    PARENT_RDR; close PARENT_WTR;
  718.           exit;
  719.           }
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  731.  
  732.  
  733.  
  734.       But you don't    actually have to make two pipe calls.  If you
  735.       have the _s_o_c_k_e_t_p_a_i_r()    system call, it    will do    this all for
  736.       you.
  737.  
  738.           #!/usr/bin/perl -w
  739.           #    pipe2 -    bidirectional communication using socketpair
  740.           #      "the best ones always    go both    ways"
  741.  
  742.           use Socket;
  743.           use IO::Handle;      # thousands of lines just for    autoflush :-(
  744.           #    We say AF_UNIX because although    *_LOCAL    is the
  745.           #    POSIX 1003.1g form of the constant, many machines
  746.           #    still don't have it.
  747.           socketpair(CHILD,    PARENT,    AF_UNIX, SOCK_STREAM, PF_UNSPEC)
  748.                       or  die "socketpair: $!";
  749.  
  750.           CHILD->autoflush(1);
  751.           PARENT->autoflush(1);
  752.  
  753.           if ($pid = fork) {
  754.           close    PARENT;
  755.           print    CHILD "Parent Pid $$ is    sending    this\n";
  756.           chomp($line =    <CHILD>);
  757.           print    "Parent    Pid $$ just read this: `$line'\n";
  758.           close    CHILD;
  759.           waitpid($pid,0);
  760.           }    else {
  761.           die "cannot fork: $!"    unless defined $pid;
  762.           close    CHILD;
  763.           chomp($line =    <PARENT>);
  764.           print    "Child Pid $$ just read    this: `$line'\n";
  765.           print    PARENT "Child Pid $$ is    sending    this\n";
  766.           close    PARENT;
  767.           exit;
  768.           }
  769.  
  770.  
  771.      SSSSoooocccckkkkeeeettttssss:::: CCCClllliiiieeeennnntttt////SSSSeeeerrrrvvvveeeerrrr CCCCoooommmmmmmmuuuunnnniiiiccccaaaattttiiiioooonnnn
  772.       While    not limited to Unix-derived operating systems (e.g.,
  773.       WinSock on PCs provides socket support, as do    some VMS
  774.       libraries), you may not have sockets on your system, in
  775.       which    case this section probably isn't going to do you much
  776.       good.     With sockets, you can do both virtual circuits    (i.e.,
  777.       TCP streams) and datagrams (i.e., UDP    packets).  You may be
  778.       able to do even more depending on your system.
  779.  
  780.       The Perl function calls for dealing with sockets have    the
  781.       same names as    the corresponding system calls in C, but their
  782.       arguments tend to differ for two reasons: first, Perl
  783.       filehandles work differently than C file descriptors.
  784.       Second, Perl already knows the length    of its strings,    so you
  785.       don't    need to    pass that information.
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  797.  
  798.  
  799.  
  800.       One of the major problems with old socket code in Perl was
  801.       that it used hard-coded values for some of the constants,
  802.       which    severely hurt portability.  If you ever    see code that
  803.       does anything    like explicitly    setting    $AF_INET = 2, you know
  804.       you're in for    big trouble:  An immeasurably superior
  805.       approach is to use the Socket    module,    which more reliably
  806.       grants access    to various constants and functions you'll
  807.       need.
  808.  
  809.       If you're not    writing    a server/client    for an existing
  810.       protocol like    NNTP or    SMTP, you should give some thought to
  811.       how your server will know when the client has    finished
  812.       talking, and vice-versa.  Most protocols are based on    one-
  813.       line messages    and responses (so one party knows the other
  814.       has finished when a "\n" is received)    or multi-line messages
  815.       and responses    that end with a    period on an empty line
  816.       ("\n.\n" terminates a    message/response).
  817.  
  818.       IIIInnnntttteeeerrrrnnnneeeetttt LLLLiiiinnnneeee    TTTTeeeerrrrmmmmiiiinnnnaaaattttoooorrrrssss
  819.  
  820.       The Internet line terminator is "\015\012".  Under ASCII
  821.       variants of Unix, that could usually be written as "\r\n",
  822.       but under other systems, "\r\n" might    at times be
  823.       "\015\015\012", "\012\012\015", or something completely
  824.       different.  The standards specify writing "\015\012" to be
  825.       conformant (be strict    in what    you provide), but they also
  826.       recommend accepting a    lone "\012" on input (but be lenient
  827.       in what you require).     We haven't always been    very good
  828.       about    that in    the code in this manpage, but unless you're on
  829.       a Mac, you'll    probably be ok.
  830.  
  831.       IIIInnnntttteeeerrrrnnnneeeetttt TTTTCCCCPPPP CCCClllliiiieeeennnnttttssss aaaannnndddd SSSSeeeerrrrvvvveeeerrrrssss
  832.  
  833.       Use Internet-domain sockets when you want to do client-
  834.       server communication that might extend to machines outside
  835.       of your own system.
  836.  
  837.       Here's a sample TCP client using Internet-domain sockets:
  838.  
  839.           #!/usr/bin/perl -w
  840.           use strict;
  841.           use Socket;
  842.           my ($remote,$port, $iaddr, $paddr, $proto, $line);
  843.  
  844.           $remote  = shift || 'localhost';
  845.           $port    = shift || 2345;     # random port
  846.           if ($port    =~ /\D/) { $port = getservbyname($port,    'tcp') }
  847.           die "No port" unless $port;
  848.           $iaddr   = inet_aton($remote)          || die "no host: $remote";
  849.           $paddr   = sockaddr_in($port, $iaddr);
  850.  
  851.  
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  863.  
  864.  
  865.  
  866.           $proto   = getprotobyname('tcp');
  867.           socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
  868.           connect(SOCK, $paddr)    || die "connect:    $!";
  869.           while (defined($line = <SOCK>)) {
  870.           print    $line;
  871.           }
  872.  
  873.           close (SOCK)          || die "close: $!";
  874.           exit;
  875.  
  876.       And here's a corresponding server to go along    with it.
  877.       We'll    leave the address as INADDR_ANY    so that    the kernel can
  878.       choose the appropriate interface on multihomed hosts.     If
  879.       you want sit on a particular interface (like the external
  880.       side of a gateway or firewall    machine), you should fill this
  881.       in with your real address instead.
  882.  
  883.           #!/usr/bin/perl -Tw
  884.           use strict;
  885.           BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  886.           use Socket;
  887.           use Carp;
  888.           $EOL = "\015\012";
  889.  
  890.           sub logmsg { print "$0 $$: @_ at ", scalar localtime, "\n" }
  891.  
  892.           my $port = shift || 2345;
  893.           my $proto    = getprotobyname('tcp');
  894.           $port = $1 if $port =~ /(\d+)/; #    untaint    port number
  895.  
  896.           socket(Server, PF_INET, SOCK_STREAM, $proto)      || die "socket: $!";
  897.           setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
  898.                           pack("l", 1))      || die "setsockopt: $!";
  899.           bind(Server, sockaddr_in($port, INADDR_ANY))      || die "bind:    $!";
  900.           listen(Server,SOMAXCONN)                  || die "listen: $!";
  901.  
  902.           logmsg "server started on    port $port";
  903.  
  904.           my $paddr;
  905.  
  906.           $SIG{CHLD} = \&REAPER;
  907.  
  908.           for ( ; $paddr = accept(Client,Server); close Client) {
  909.           my($port,$iaddr) = sockaddr_in($paddr);
  910.           my $name = gethostbyaddr($iaddr,AF_INET);
  911.  
  912.           logmsg "connection from $name    [",
  913.               inet_ntoa($iaddr), "]
  914.               at port $port";
  915.  
  916.  
  917.  
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  929.  
  930.  
  931.  
  932.           print    Client "Hello there, $name, it's now ",
  933.                   scalar localtime, $EOL;
  934.           }
  935.  
  936.       And here's a multithreaded version.  It's multithreaded in
  937.       that like most typical servers, it spawns (forks) a slave
  938.       server to handle the client request so that the master
  939.       server can quickly go    back to    service    a new client.
  940.  
  941.           #!/usr/bin/perl -Tw
  942.           use strict;
  943.           BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  944.           use Socket;
  945.           use Carp;
  946.           $EOL = "\015\012";
  947.  
  948.           sub spawn;  # forward declaration
  949.           sub logmsg { print "$0 $$: @_ at ", scalar localtime, "\n" }
  950.  
  951.           my $port = shift || 2345;
  952.           my $proto    = getprotobyname('tcp');
  953.           $port = $1 if $port =~ /(\d+)/; #    untaint    port number
  954.  
  955.           socket(Server, PF_INET, SOCK_STREAM, $proto)      || die "socket: $!";
  956.           setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
  957.                           pack("l", 1))      || die "setsockopt: $!";
  958.           bind(Server, sockaddr_in($port, INADDR_ANY))      || die "bind:    $!";
  959.           listen(Server,SOMAXCONN)                  || die "listen: $!";
  960.  
  961.           logmsg "server started on    port $port";
  962.  
  963.           my $waitedpid = 0;
  964.           my $paddr;
  965.  
  966.           sub REAPER {
  967.           $waitedpid = wait;
  968.           $SIG{CHLD} = \&REAPER;  # loathe sysV
  969.           logmsg "reaped $waitedpid" . ($? ? " with exit $?" : '');
  970.           }
  971.  
  972.           $SIG{CHLD} = \&REAPER;
  973.  
  974.           for ( $waitedpid = 0;
  975.             ($paddr = accept(Client,Server)) ||    $waitedpid;
  976.             $waitedpid = 0, close Client)
  977.           {
  978.           next if $waitedpid and not $paddr;
  979.           my($port,$iaddr) = sockaddr_in($paddr);
  980.           my $name = gethostbyaddr($iaddr,AF_INET);
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  995.  
  996.  
  997.  
  998.           logmsg "connection from $name    [",
  999.               inet_ntoa($iaddr), "]
  1000.               at port $port";
  1001.  
  1002.           spawn    sub {
  1003.               print "Hello there, $name, it's now ", scalar localtime, $EOL;
  1004.               exec '/usr/games/fortune'          # XXX: `wrong' line terminators
  1005.               or confess "can't exec fortune: $!";
  1006.           };
  1007.  
  1008.           }
  1009.  
  1010.           sub spawn    {
  1011.           my $coderef =    shift;
  1012.  
  1013.           unless (@_ ==    0 && $coderef && ref($coderef) eq 'CODE') {
  1014.               confess "usage: spawn CODEREF";
  1015.           }
  1016.  
  1017.           my $pid;
  1018.           if (!defined($pid = fork)) {
  1019.               logmsg "cannot fork: $!";
  1020.               return;
  1021.           } elsif ($pid) {
  1022.               logmsg "begat $pid";
  1023.               return; #    I'm the    parent
  1024.           }
  1025.           # else I'm the child -- go spawn
  1026.  
  1027.           open(STDIN,  "<&Client")   ||    die "can't dup client to stdin";
  1028.           open(STDOUT, ">&Client")   ||    die "can't dup client to stdout";
  1029.           ## open(STDERR, ">&STDOUT") || die "can't dup    stdout to stderr";
  1030.           exit &$coderef();
  1031.           }
  1032.  
  1033.       This server takes the    trouble    to clone off a child version
  1034.       via _f_o_r_k() for each incoming request.     That way it can
  1035.       handle many requests at once,    which you might    not always
  1036.       want.     Even if you don't _f_o_r_k(), the _l_i_s_t_e_n()    will allow
  1037.       that many pending connections.  Forking servers have to be
  1038.       particularly careful about cleaning up their dead children
  1039.       (called "zombies" in Unix parlance), because otherwise
  1040.       you'll quickly fill up your process table.
  1041.  
  1042.       We suggest that you use the ----TTTT flag to use taint checking
  1043.       (see the _p_e_r_l_s_e_c manpage) even if we aren't running setuid
  1044.       or setgid.  This is always a good idea for servers and other
  1045.       programs run on behalf of someone else (like CGI scripts),
  1046.       because it lessens the chances that people from the outside
  1047.       will be able to compromise your system.
  1048.  
  1049.       Let's    look at    another    TCP client.  This one connects to the
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1061.  
  1062.  
  1063.  
  1064.       TCP "time" service on    a number of different machines and
  1065.       shows    how far    their clocks differ from the system on which
  1066.       it's being run:
  1067.  
  1068.           #!/usr/bin/perl  -w
  1069.           use strict;
  1070.           use Socket;
  1071.  
  1072.           my $SECS_of_70_YEARS = 2208988800;
  1073.           sub ctime    { scalar localtime(shift) }
  1074.  
  1075.           my $iaddr    = gethostbyname('localhost');
  1076.           my $proto    = getprotobyname('tcp');
  1077.           my $port = getservbyname('time', 'tcp');
  1078.           my $paddr    = sockaddr_in(0, $iaddr);
  1079.           my($host);
  1080.  
  1081.           $| = 1;
  1082.           printf "%-24s %8s    %s\n",    "localhost", 0,    ctime(time());
  1083.  
  1084.           foreach $host (@ARGV) {
  1085.           printf "%-24s    ", $host;
  1086.           my $hisiaddr = inet_aton($host)     || die "unknown host";
  1087.           my $hispaddr = sockaddr_in($port, $hisiaddr);
  1088.           socket(SOCKET, PF_INET, SOCK_STREAM, $proto)     || die    "socket: $!";
  1089.           connect(SOCKET, $hispaddr)          || die "bind: $!";
  1090.           my $rtime = '       ';
  1091.           read(SOCKET, $rtime, 4);
  1092.           close(SOCKET);
  1093.           my $histime =    unpack("N", $rtime) - $SECS_of_70_YEARS    ;
  1094.           printf "%8d %s\n", $histime -    time, ctime($histime);
  1095.           }
  1096.  
  1097.  
  1098.       UUUUnnnniiiixxxx----DDDDoooommmmaaaaiiiinnnn TTTTCCCCPPPP CCCClllliiiieeeennnnttttssss aaaannnndddd SSSSeeeerrrrvvvveeeerrrrssss
  1099.  
  1100.       That's fine for Internet-domain clients and servers, but
  1101.       what about local communications?  While you can use the same
  1102.       setup, sometimes you don't want to.  Unix-domain sockets are
  1103.       local    to the current host, and are often used    internally to
  1104.       implement pipes.  Unlike Internet domain sockets, Unix
  1105.       domain sockets can show up in    the file system    with an    _l_s(1)
  1106.       listing.
  1107.  
  1108.           %    ls -l /dev/log
  1109.           srw-rw-rw-  1 root        0 Oct 31 07:23 /dev/log
  1110.  
  1111.       You can test for these with Perl's ----SSSS    file test:
  1112.  
  1113.           unless ( -S '/dev/log' ) {
  1114.           die "something's wicked with the print system";
  1115.           }
  1116.  
  1117.  
  1118.  
  1119.      Page 17                        (printed 10/23/98)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1127.  
  1128.  
  1129.  
  1130.       Here's a sample Unix-domain client:
  1131.  
  1132.           #!/usr/bin/perl -w
  1133.           use Socket;
  1134.           use strict;
  1135.           my ($rendezvous, $line);
  1136.  
  1137.           $rendezvous = shift || '/tmp/catsock';
  1138.           socket(SOCK, PF_UNIX, SOCK_STREAM, 0)      || die "socket: $!";
  1139.           connect(SOCK, sockaddr_un($rendezvous))      || die "connect: $!";
  1140.           while (defined($line = <SOCK>)) {
  1141.           print    $line;
  1142.           }
  1143.           exit;
  1144.  
  1145.       And here's a corresponding server.  You don't    have to    worry
  1146.       about    silly network terminators here because Unix domain
  1147.       sockets are guaranteed to be on the localhost, and thus
  1148.       everything works right.
  1149.  
  1150.           #!/usr/bin/perl -Tw
  1151.           use strict;
  1152.           use Socket;
  1153.           use Carp;
  1154.  
  1155.           BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  1156.           sub logmsg { print "$0 $$: @_ at ", scalar localtime, "\n" }
  1157.  
  1158.           my $NAME = '/tmp/catsock';
  1159.           my $uaddr    = sockaddr_un($NAME);
  1160.           my $proto    = getprotobyname('tcp');
  1161.  
  1162.           socket(Server,PF_UNIX,SOCK_STREAM,0)      || die "socket: $!";
  1163.           unlink($NAME);
  1164.           bind  (Server, $uaddr)              || die "bind:    $!";
  1165.           listen(Server,SOMAXCONN)              || die "listen: $!";
  1166.  
  1167.           logmsg "server started on    $NAME";
  1168.  
  1169.           my $waitedpid;
  1170.  
  1171.           sub REAPER {
  1172.           $waitedpid = wait;
  1173.           $SIG{CHLD} = \&REAPER;  # loathe sysV
  1174.           logmsg "reaped $waitedpid" . ($? ? " with exit $?" : '');
  1175.           }
  1176.  
  1177.           $SIG{CHLD} = \&REAPER;
  1178.  
  1179.  
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.      Page 18                        (printed 10/23/98)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1193.  
  1194.  
  1195.  
  1196.           for ( $waitedpid = 0;
  1197.             accept(Client,Server) || $waitedpid;
  1198.             $waitedpid = 0, close Client)
  1199.           {
  1200.           next if $waitedpid;
  1201.           logmsg "connection on    $NAME";
  1202.           spawn    sub {
  1203.               print "Hello there, it's now ", scalar localtime,    "\n";
  1204.               exec '/usr/games/fortune'    or die "can't exec fortune: $!";
  1205.           };
  1206.           }
  1207.  
  1208.       As you see, it's remarkably similar to the Internet domain
  1209.       TCP server, so much so, in fact, that    we've omitted several
  1210.       duplicate functions--_s_p_a_w_n(),    _l_o_g_m_s_g(), _c_t_i_m_e(), and
  1211.       _R_E_A_P_E_R()--which are exactly the same as in the other server.
  1212.  
  1213.       So why would you ever    want to    use a Unix domain socket
  1214.       instead of a simpler named pipe?  Because a named pipe
  1215.       doesn't give you sessions.  You can't    tell one process's
  1216.       data from another's.    With socket programming, you get a
  1217.       separate session for each client: that's why _a_c_c_e_p_t()    takes
  1218.       two arguments.
  1219.  
  1220.       For example, let's say that you have a long running database
  1221.       server daemon    that you want folks from the World Wide    Web to
  1222.       be able to access, but only if they go through a CGI
  1223.       interface.  You'd have a small, simple CGI program that does
  1224.       whatever checks and logging you feel like, and then acts as
  1225.       a Unix-domain    client and connects to your private server.
  1226.  
  1227.      TTTTCCCCPPPP CCCClllliiiieeeennnnttttssss wwwwiiiitttthhhh IIIIOOOO::::::::SSSSoooocccckkkkeeeetttt
  1228.       For those preferring a higher-level interface    to socket
  1229.       programming, the IO::Socket module provides an object-
  1230.       oriented approach.  IO::Socket is included as    part of    the
  1231.       standard Perl    distribution as    of the 5.004 release.  If
  1232.       you're running an earlier version of Perl, just fetch
  1233.       IO::Socket from CPAN,    where you'll also find find modules
  1234.       providing easy interfaces to the following systems: DNS,
  1235.       FTP, Ident (RFC 931),    NIS and    NISPlus, NNTP, Ping, POP3,
  1236.       SMTP,    SNMP, SSLeay, Telnet, and Time--just to    name a few.
  1237.  
  1238.       AAAA SSSSiiiimmmmpppplllleeee CCCClllliiiieeeennnntttt
  1239.  
  1240.       Here's a client that creates a TCP connection    to the
  1241.       "daytime" service at port 13 of the host name    "localhost"
  1242.       and prints out everything that the server there cares    to
  1243.       provide.
  1244.  
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.      Page 19                        (printed 10/23/98)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1259.  
  1260.  
  1261.  
  1262.           #!/usr/bin/perl -w
  1263.           use IO::Socket;
  1264.           $remote =    IO::Socket::INET->new(
  1265.                   Proto       => "tcp",
  1266.                   PeerAddr => "localhost",
  1267.                   PeerPort => "daytime(13)",
  1268.                   )
  1269.                 or die "cannot connect to daytime port at localhost";
  1270.           while ( <$remote>    ) { print }
  1271.  
  1272.       When you run this program, you should    get something back
  1273.       that looks like this:
  1274.  
  1275.           Wed May 14 08:40:46 MDT 1997
  1276.  
  1277.       Here are what    those parameters to the    new constructor    mean:
  1278.  
  1279.       Proto
  1280.            This is which protocol to use.  In this case, the
  1281.            socket handle returned will be connected    to a TCP
  1282.            socket, because we want a stream-oriented connection,
  1283.            that is,    one that acts pretty much like a plain old
  1284.            file.  Not all sockets are this of this type.  For
  1285.            example,    the UDP    protocol can be    used to    make a
  1286.            datagram    socket,    used for message-passing.
  1287.  
  1288.       PeerAddr
  1289.            This is the name    or Internet address of the remote host
  1290.            the server is running on.  We could have    specified a
  1291.            longer name like    "www.perl.com",    or an address like
  1292.            "204.148.40.9".    For demonstration purposes, we've used
  1293.            the special hostname "localhost", which should always
  1294.            mean the    current    machine    you're running on.  The
  1295.            corresponding Internet address for localhost is
  1296.            "127.1",    if you'd rather    use that.
  1297.  
  1298.       PeerPort
  1299.            This is the service name    or port    number we'd like to
  1300.            connect to.  We could have gotten away with using just
  1301.            "daytime" on systems with a well-configured system
  1302.            services    file,[FOOTNOTE:    The system services file is in
  1303.            /_e_t_c/_s_e_r_v_i_c_e_s under Unix] but just in case, we've
  1304.            specified the port number (13) in parentheses.  Using
  1305.            just the    number would also have worked, but constant
  1306.            numbers make careful programmers    nervous.
  1307.  
  1308.       Notice how the return    value from the new constructor is used
  1309.       as a filehandle in the while loop?  That's what's called an
  1310.       indirect filehandle, a scalar    variable containing a
  1311.       filehandle.  You can use it the same way you would a normal
  1312.       filehandle.  For example, you    can read one line from it this
  1313.       way:
  1314.  
  1315.  
  1316.  
  1317.      Page 20                        (printed 10/23/98)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1325.  
  1326.  
  1327.  
  1328.           $line = <$handle>;
  1329.  
  1330.       all remaining    lines from is this way:
  1331.  
  1332.           @lines = <$handle>;
  1333.  
  1334.       and send a line of data to it    this way:
  1335.  
  1336.           print $handle "some data\n";
  1337.  
  1338.  
  1339.       AAAA WWWWeeeebbbbggggeeeetttt CCCClllliiiieeeennnntttt
  1340.  
  1341.       Here's a simple client that takes a remote host to fetch a
  1342.       document from, and then a list of documents to get from that
  1343.       host.     This is a more    interesting client than    the previous
  1344.       one because it first sends something to the server before
  1345.       fetching the server's    response.
  1346.  
  1347.           #!/usr/bin/perl -w
  1348.           use IO::Socket;
  1349.           unless (@ARGV > 1) { die "usage: $0 host document    ..." }
  1350.           $host = shift(@ARGV);
  1351.           $EOL = "\015\012";
  1352.           $BLANK = $EOL x 2;
  1353.           foreach $document    ( @ARGV    ) {
  1354.           $remote = IO::Socket::INET->new( Proto     =>    "tcp",
  1355.                            PeerAddr  =>    $host,
  1356.                            PeerPort  =>    "http(80)",
  1357.                           );
  1358.           unless ($remote) { die "cannot connect to http daemon    on $host" }
  1359.           $remote->autoflush(1);
  1360.           print    $remote    "GET $document HTTP/1.0" . $BLANK;
  1361.           while    ( <$remote> ) {    print }
  1362.           close    $remote;
  1363.           }
  1364.  
  1365.       The web server handing the "http" service, which is assumed
  1366.       to be    at its standard    port, number 80.  If your the web
  1367.       server you're    trying to connect to is    at a different port
  1368.       (like    1080 or    8080), you should specify as the named-
  1369.       parameter pair, PeerPort => 8080.  The autoflush method is
  1370.       used on the socket because otherwise the system would    buffer
  1371.       up the output    we sent    it.  (If you're    on a Mac, you'll also
  1372.       need to change every "\n" in your code that sends data over
  1373.       the network to be a "\015\012" instead.)
  1374.  
  1375.       Connecting to    the server is only the first part of the
  1376.       process: once    you have the connection, you have to use the
  1377.       server's language.  Each server on the network has its own
  1378.       little command language that it expects as input.  The
  1379.       string that we send to the server starting with "GET"    is in
  1380.  
  1381.  
  1382.  
  1383.      Page 21                        (printed 10/23/98)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1391.  
  1392.  
  1393.  
  1394.       HTTP syntax.    In this    case, we simply    request    each specified
  1395.       document.  Yes, we really are    making a new connection    for
  1396.       each document, even though it's the same host.  That's the
  1397.       way you always used to have to speak HTTP.  Recent versions
  1398.       of web browsers may request that the remote server leave the
  1399.       connection open a little while, but the server doesn't have
  1400.       to honor such    a request.
  1401.  
  1402.       Here's an example of running that program, which we'll call
  1403.       _w_e_b_g_e_t:
  1404.  
  1405.           %    webget www.perl.com /guanaco.html
  1406.           HTTP/1.1 404 File    Not Found
  1407.           Date: Thu, 08 May    1997 18:02:32 GMT
  1408.           Server: Apache/1.2b6
  1409.           Connection: close
  1410.           Content-type: text/html
  1411.  
  1412.           <HEAD><TITLE>404 File Not    Found</TITLE></HEAD>
  1413.           <BODY><H1>File Not Found</H1>
  1414.           The requested URL    /guanaco.html was not found on this server.<P>
  1415.           </BODY>
  1416.  
  1417.       Ok, so that's    not very interesting, because it didn't    find
  1418.       that particular document.  But a long    response wouldn't have
  1419.       fit on this page.
  1420.  
  1421.       For a    more fully-featured version of this program, you
  1422.       should look to the _l_w_p-_r_e_q_u_e_s_t program included with the LWP
  1423.       modules from CPAN.
  1424.  
  1425.       IIIInnnntttteeeerrrraaaaccccttttiiiivvvveeee CCCClllliiiieeeennnntttt wwwwiiiitttthhhh IIIIOOOO::::::::SSSSoooocccckkkkeeeetttt
  1426.  
  1427.       Well,    that's all fine    if you want to send one    command    and
  1428.       get one answer, but what about setting up something fully
  1429.       interactive, somewhat    like the way _t_e_l_n_e_t works?  That way
  1430.       you can type a line, get the answer, type a line, get    the
  1431.       answer, etc.
  1432.  
  1433.       This client is more complicated than the two we've done so
  1434.       far, but if you're on    a system that supports the powerful
  1435.       fork call, the solution isn't    that rough.  Once you've made
  1436.       the connection to whatever service you'd like    to chat    with,
  1437.       call fork to clone your process.  Each of these two
  1438.       identical process has    a very simple job to do: the parent
  1439.       copies everything from the socket to standard    output,    while
  1440.       the child simultaneously copies everything from standard
  1441.       input    to the socket.    To accomplish the same thing using
  1442.       just one process would be _m_u_c_h harder, because it's easier
  1443.       to code two processes    to do one thing    than it    is to code one
  1444.       process to do    two things.  (This keep-it-simple principle a
  1445.       cornerstones of the Unix philosophy, and good    software
  1446.  
  1447.  
  1448.  
  1449.      Page 22                        (printed 10/23/98)
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1457.  
  1458.  
  1459.  
  1460.       engineering as well, which is    probably why it's spread to
  1461.       other    systems.)
  1462.  
  1463.       Here's the code:
  1464.  
  1465.           #!/usr/bin/perl -w
  1466.           use strict;
  1467.           use IO::Socket;
  1468.           my ($host, $port,    $kidpid, $handle, $line);
  1469.  
  1470.           unless (@ARGV == 2) { die    "usage:    $0 host    port" }
  1471.           ($host, $port) = @ARGV;
  1472.  
  1473.           #    create a tcp connection    to the specified host and port
  1474.           $handle =    IO::Socket::INET->new(Proto    => "tcp",
  1475.                           PeerAddr    => $host,
  1476.                           PeerPort    => $port)
  1477.              or    die "can't connect to port $port on $host: $!";
  1478.  
  1479.           $handle->autoflush(1);          # so output gets there right away
  1480.           print STDERR "[Connected to $host:$port]\n";
  1481.  
  1482.           #    split the program into two processes, identical    twins
  1483.           die "can't fork: $!" unless defined($kidpid = fork());
  1484.  
  1485.           #    the if{} block runs only in the    parent process
  1486.           if ($kidpid) {
  1487.           # copy the socket to standard    output
  1488.           while    (defined ($line    = <$handle>)) {
  1489.               print STDOUT $line;
  1490.           }
  1491.           kill("TERM", $kidpid);          # send SIGTERM to child
  1492.           }
  1493.           #    the else{} block runs only in the child    process
  1494.           else {
  1495.           # copy standard input    to the socket
  1496.           while    (defined ($line    = <STDIN>)) {
  1497.               print $handle $line;
  1498.           }
  1499.           }
  1500.  
  1501.       The kill function in the parent's if block is    there to send
  1502.       a signal to our child    process    (current running in the    else
  1503.       block) as soon as the    remote server has closed its end of
  1504.       the connection.
  1505.  
  1506.       If the remote    server sends data a byte at time, and you need
  1507.       that data immediately    without    waiting    for a newline (which
  1508.       might    not happen), you may wish to replace the while loop in
  1509.       the parent with the following:
  1510.  
  1511.  
  1512.  
  1513.  
  1514.  
  1515.      Page 23                        (printed 10/23/98)
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1523.  
  1524.  
  1525.  
  1526.           my $byte;
  1527.           while (sysread($handle, $byte, 1)    == 1) {
  1528.           print    STDOUT $byte;
  1529.           }
  1530.  
  1531.       Making a system call for each    byte you want to read is not
  1532.       very efficient (to put it mildly) but    is the simplest    to
  1533.       explain and works reasonably well.
  1534.  
  1535.      TTTTCCCCPPPP SSSSeeeerrrrvvvveeeerrrrssss wwwwiiiitttthhhh IIIIOOOO::::::::SSSSoooocccckkkkeeeetttt
  1536.       As always, setting up    a server is little bit more involved
  1537.       than running a client.  The model is that the    server creates
  1538.       a special kind of socket that    does nothing but listen    on a
  1539.       particular port for incoming connections.  It    does this by
  1540.       calling the IO::Socket::INET->new() method with slightly
  1541.       different arguments than the client did.
  1542.  
  1543.       Proto
  1544.            This is which protocol to use.  Like our    clients, we'll
  1545.            still specify "tcp" here.
  1546.  
  1547.       LocalPort
  1548.            We specify a local port in the LocalPort    argument,
  1549.            which we    didn't do for the client.  This    is service
  1550.            name or port number for which you want to be the
  1551.            server. (Under Unix, ports under    1024 are restricted to
  1552.            the superuser.)    In our sample, we'll use port 9000,
  1553.            but you can use any port    that's not currently in    use on
  1554.            your system.  If    you try    to use one already in used,
  1555.            you'll get an "Address already in use" message. Under
  1556.            Unix, the netstat -a command will show which services
  1557.            current have servers.
  1558.  
  1559.       Listen
  1560.            The Listen parameter is set to the maximum number of
  1561.            pending connections we can accept until we turn away
  1562.            incoming    clients.  Think    of it as a call-waiting    queue
  1563.            for your    telephone.  The    low-level Socket module    has a
  1564.            special symbol for the system maximum, which is
  1565.            SOMAXCONN.
  1566.  
  1567.       Reuse
  1568.            The Reuse parameter is needed so    that we    restart    our
  1569.            server manually without waiting a few minutes to    allow
  1570.            system buffers to clear out.
  1571.  
  1572.       Once the generic server socket has been created using    the
  1573.       parameters listed above, the server then waits for a new
  1574.       client to connect to it.  The    server blocks in the accept
  1575.       method, which    eventually an bidirectional connection to the
  1576.       remote client.  (Make    sure to    autoflush this handle to
  1577.       circumvent buffering.)
  1578.  
  1579.  
  1580.  
  1581.      Page 24                        (printed 10/23/98)
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1589.  
  1590.  
  1591.  
  1592.       To add to user-friendliness, our server prompts the user for
  1593.       commands.  Most servers don't    do this.  Because of the
  1594.       prompt without a newline, you'll have    to use the sysread
  1595.       variant of the interactive client above.
  1596.  
  1597.       This server accepts one of five different commands, sending
  1598.       output back to the client.  Note that    unlike most network
  1599.       servers, this    one only handles one incoming client at    a
  1600.       time.     Multithreaded servers are covered in Chapter 6    of the
  1601.       Camel    as well    as later in this manpage.
  1602.  
  1603.       Here's the code.  We'll
  1604.  
  1605.        #!/usr/bin/perl -w
  1606.        use IO::Socket;
  1607.        use Net::hostent;          # for    OO version of gethostbyaddr
  1608.  
  1609.        $PORT = 9000;          # pick something not in use
  1610.  
  1611.        $server = IO::Socket::INET->new( Proto     => 'tcp',
  1612.                         LocalPort => $PORT,
  1613.                         Listen    => SOMAXCONN,
  1614.                         Reuse     => 1);
  1615.  
  1616.        die "can't setup server" unless $server;
  1617.        print "[Server $0 accepting clients]\n";
  1618.  
  1619.        while ($client = $server->accept()) {
  1620.          $client->autoflush(1);
  1621.          print $client "Welcome to $0; type    help for command list.\n";
  1622.          $hostinfo = gethostbyaddr($client->peeraddr);
  1623.          printf "[Connect from %s]\n", $hostinfo->name || $client->peerhost;
  1624.          print $client "Command? ";
  1625.          while ( <$client>)    {
  1626.            next unless /\S/;       # blank line
  1627.            if    (/quit|exit/i)    { last;                       }
  1628.            elsif (/date|time/i)    { printf    $client    "%s\n",    scalar localtime;  }
  1629.            elsif (/who/i )           { print    $client    `who 2>&1`;           }
  1630.            elsif (/cookie/i    )      { print    $client    `/usr/games/fortune 2>&1`; }
  1631.            elsif (/motd/i )           { print    $client    `cat /etc/motd 2>&1`;       }
  1632.            else {
  1633.          print $client "Commands: quit date who    cookie motd\n";
  1634.            }
  1635.          } continue    {
  1636.         print $client "Command?    ";
  1637.          }
  1638.          close $client;
  1639.        }
  1640.  
  1641.  
  1642.      UUUUDDDDPPPP:::: MMMMeeeessssssssaaaaggggeeee PPPPaaaassssssssiiiinnnngggg
  1643.       Another kind of client-server    setup is one that uses not
  1644.  
  1645.  
  1646.  
  1647.      Page 25                        (printed 10/23/98)
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1655.  
  1656.  
  1657.  
  1658.       connections, but messages.  UDP communications involve much
  1659.       lower    overhead but also provide less reliability, as there
  1660.       are no promises that messages    will arrive at all, let    alone
  1661.       in order and unmangled.  Still, UDP offers some advantages
  1662.       over TCP, including being able to "broadcast"    or "multicast"
  1663.       to a whole bunch of destination hosts    at once    (usually on
  1664.       your local subnet).  If you find yourself overly concerned
  1665.       about    reliability and    start building checks into your
  1666.       message system, then you probably should use just TCP    to
  1667.       start    with.
  1668.  
  1669.       Here's a UDP program similar to the sample Internet TCP
  1670.       client given earlier.     However, instead of checking one host
  1671.       at a time, the UDP version will check    many of    them
  1672.       asynchronously by simulating a multicast and then using
  1673.       _s_e_l_e_c_t() to do a timed-out wait for I/O.  To do something
  1674.       similar with TCP, you'd have to use a    different socket
  1675.       handle for each host.
  1676.  
  1677.           #!/usr/bin/perl -w
  1678.           use strict;
  1679.           use Socket;
  1680.           use Sys::Hostname;
  1681.  
  1682.           my ( $count, $hisiaddr, $hispaddr, $histime,
  1683.            $host, $iaddr, $paddr, $port, $proto,
  1684.            $rin, $rout,    $rtime,    $SECS_of_70_YEARS);
  1685.  
  1686.           $SECS_of_70_YEARS         = 2208988800;
  1687.  
  1688.           $iaddr = gethostbyname(hostname());
  1689.           $proto = getprotobyname('udp');
  1690.           $port = getservbyname('time', 'udp');
  1691.           $paddr = sockaddr_in(0, $iaddr); # 0 means let kernel pick
  1692.  
  1693.           socket(SOCKET, PF_INET, SOCK_DGRAM, $proto)   || die "socket: $!";
  1694.           bind(SOCKET, $paddr)                || die "bind: $!";
  1695.  
  1696.           $| = 1;
  1697.           printf "%-12s %8s    %s\n",    "localhost", 0,    scalar localtime time;
  1698.           $count = 0;
  1699.           for $host    (@ARGV)    {
  1700.           $count++;
  1701.           $hisiaddr = inet_aton($host)      || die "unknown host";
  1702.           $hispaddr = sockaddr_in($port, $hisiaddr);
  1703.           defined(send(SOCKET, 0, 0, $hispaddr))    || die "send $host:    $!";
  1704.           }
  1705.  
  1706.           $rin = '';
  1707.           vec($rin,    fileno(SOCKET),    1) = 1;
  1708.  
  1709.  
  1710.  
  1711.  
  1712.  
  1713.      Page 26                        (printed 10/23/98)
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1721.  
  1722.  
  1723.  
  1724.           #    timeout    after 10.0 seconds
  1725.           while ($count && select($rout = $rin, undef, undef, 10.0)) {
  1726.           $rtime = '';
  1727.           ($hispaddr = recv(SOCKET, $rtime, 4, 0))      || die "recv:    $!";
  1728.           ($port, $hisiaddr) = sockaddr_in($hispaddr);
  1729.           $host    = gethostbyaddr($hisiaddr, AF_INET);
  1730.           $histime = unpack("N", $rtime) - $SECS_of_70_YEARS ;
  1731.           printf "%-12s    ", $host;
  1732.           printf "%8d %s\n", $histime -    time, scalar localtime($histime);
  1733.           $count--;
  1734.           }
  1735.  
  1736.  
  1737.      SSSSyyyyssssVVVV IIIIPPPPCCCC
  1738.       While    System V IPC isn't so widely used as sockets, it still
  1739.       has some interesting uses.  You can't, however, effectively
  1740.       use SysV IPC or Berkeley _m_m_a_p() to have shared memory    so as
  1741.       to share a variable amongst several processes.  That's
  1742.       because Perl would reallocate    your string when you weren't
  1743.       wanting it to.
  1744.  
  1745.       Here's a small example showing shared    memory usage.
  1746.  
  1747.           use IPC::SysV qw(IPC_PRIVATE IPC_RMID S_IRWXU S_IRWXG S_IRWXO);
  1748.  
  1749.           $size = 2000;
  1750.           $key = shmget(IPC_PRIVATE, $size,    S_IRWXU|S_IRWXG|S_IRWXO) || die    "$!";
  1751.           print "shm key $key\n";
  1752.  
  1753.           $message = "Message #1";
  1754.           shmwrite($key, $message, 0, 60) || die "$!";
  1755.           print "wrote: '$message'\n";
  1756.           shmread($key, $buff, 0, 60) || die "$!";
  1757.           print "read : '$buff'\n";
  1758.  
  1759.           #    the buffer of shmread is zero-character    end-padded.
  1760.           substr($buff, index($buff, "\0"))    = '';
  1761.           print "un" unless    $buff eq $message;
  1762.           print "swell\n";
  1763.  
  1764.           print "deleting shm $key\n";
  1765.           shmctl($key, IPC_RMID, 0)    || die "$!";
  1766.  
  1767.       Here's an example of a semaphore:
  1768.  
  1769.           use IPC::SysV qw(IPC_CREAT);
  1770.  
  1771.           $IPC_KEY = 1234;
  1772.           $key = semget($IPC_KEY, 10, 0666 | IPC_CREAT ) ||    die "$!";
  1773.           print "shm key $key\n";
  1774.  
  1775.       Put this code    in a separate file to be run in    more than one
  1776.  
  1777.  
  1778.  
  1779.      Page 27                        (printed 10/23/98)
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1787.  
  1788.  
  1789.  
  1790.       process.  Call the file _t_a_k_e:
  1791.  
  1792.           #    create a semaphore
  1793.  
  1794.           $IPC_KEY = 1234;
  1795.           $key = semget($IPC_KEY,  0 , 0 );
  1796.           die if !defined($key);
  1797.  
  1798.           $semnum =    0;
  1799.           $semflag = 0;
  1800.  
  1801.           #    'take' semaphore
  1802.           #    wait for semaphore to be zero
  1803.           $semop = 0;
  1804.           $opstring1 = pack("sss", $semnum,    $semop,    $semflag);
  1805.  
  1806.           #    Increment the semaphore    count
  1807.           $semop = 1;
  1808.           $opstring2 = pack("sss", $semnum,    $semop,     $semflag);
  1809.           $opstring    = $opstring1 . $opstring2;
  1810.  
  1811.           semop($key,$opstring) || die "$!";
  1812.  
  1813.       Put this code    in a separate file to be run in    more than one
  1814.       process.  Call this file _g_i_v_e:
  1815.  
  1816.           #    'give' the semaphore
  1817.           #    run this in the    original process and you will see
  1818.           #    that the second    process    continues
  1819.  
  1820.           $IPC_KEY = 1234;
  1821.           $key = semget($IPC_KEY, 0, 0);
  1822.           die if !defined($key);
  1823.  
  1824.           $semnum =    0;
  1825.           $semflag = 0;
  1826.  
  1827.           #    Decrement the semaphore    count
  1828.           $semop = -1;
  1829.           $opstring    = pack("sss", $semnum, $semop, $semflag);
  1830.  
  1831.           semop($key,$opstring) || die "$!";
  1832.  
  1833.       The SysV IPC code above was written long ago,    and it's
  1834.       definitely clunky looking.  For a more modern    look, see the
  1835.       IPC::SysV module which is included with Perl starting    from
  1836.       Perl 5.005.
  1837.  
  1838.      NNNNOOOOTTTTEEEESSSS
  1839.       Most of these    routines quietly but politely return undef
  1840.       when they fail instead of causing your program to die    right
  1841.       then and there due to    an uncaught exception.    (Actually,
  1842.  
  1843.  
  1844.  
  1845.      Page 28                        (printed 10/23/98)
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1853.  
  1854.  
  1855.  
  1856.       some of the new _S_o_c_k_e_t conversion functions  _c_r_o_a_k() on bad
  1857.       arguments.)  It is therefore essential to check return
  1858.       values from these functions.    Always begin your socket
  1859.       programs this    way for    optimal    success, and don't forget to
  1860.       add ----TTTT taint checking    flag to    the #! line for    servers:
  1861.  
  1862.           #!/usr/bin/perl -Tw
  1863.           use strict;
  1864.           use sigtrap;
  1865.           use Socket;
  1866.  
  1867.  
  1868.      BBBBUUUUGGGGSSSS
  1869.       All these routines create system-specific portability
  1870.       problems.  As    noted elsewhere, Perl is at the    mercy of your
  1871.       C libraries for much of its system behaviour.     It's probably
  1872.       safest to assume broken SysV semantics for signals and to
  1873.       stick    with simple TCP    and UDP    socket operations; e.g., don't
  1874.       try to pass open file    descriptors over a local UDP datagram
  1875.       socket if you    want your code to stand    a chance of being
  1876.       portable.
  1877.  
  1878.       As mentioned in the signals section, because few vendors
  1879.       provide C libraries that are safely re-entrant, the prudent
  1880.       programmer will do little else within    a handler beyond
  1881.       setting a numeric variable that already exists; or, if
  1882.       locked into a    slow (restarting) system call, using _d_i_e() to
  1883.       raise    an exception and _l_o_n_g_j_m_p(3) out.  In fact, even    these
  1884.       may in some cases cause a core dump.    It's probably best to
  1885.       avoid    signals    except where they are absolutely inevitable.
  1886.       This will be addressed in a future release of    Perl.
  1887.  
  1888.      AAAAUUUUTTTTHHHHOOOORRRR
  1889.       Tom Christiansen, with occasional vestiges of    Larry Wall's
  1890.       original version and suggestions from    the Perl Porters.
  1891.  
  1892.      SSSSEEEEEEEE AAAALLLLSSSSOOOO
  1893.       There's a lot    more to    networking than    this, but this should
  1894.       get you started.
  1895.  
  1896.       For intrepid programmers, the    indispensable textbook is _U_n_i_x
  1897.       _N_e_t_w_o_r_k _P_r_o_g_r_a_m_m_i_n_g by W. Richard Stevens (published by
  1898.       Addison-Wesley).  Note that most books on networking address
  1899.       networking from the perspective of a C programmer;
  1900.       translation to Perl is left as an exercise for the reader.
  1901.  
  1902.       The _I_O::_S_o_c_k_e_t(3) manpage describes the object library, and
  1903.       the _S_o_c_k_e_t(3)    manpage    describes the low-level    interface to
  1904.       sockets.  Besides the    obvious    functions in the _p_e_r_l_f_u_n_c
  1905.       manpage, you should also check out the _m_o_d_u_l_e_s file at your
  1906.       nearest CPAN site.  (See the _p_e_r_l_m_o_d_l_i_b manpage or best yet,
  1907.       the _P_e_r_l _F_A_Q for a description of what CPAN is and where to
  1908.  
  1909.  
  1910.  
  1911.      Page 29                        (printed 10/23/98)
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918.      PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))         22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))        PPPPEEEERRRRLLLLIIIIPPPPCCCC((((1111))))
  1919.  
  1920.  
  1921.  
  1922.       get it.)
  1923.  
  1924.       Section 5 of the _m_o_d_u_l_e_s file    is devoted to "Networking,
  1925.       Device Control (modems), and Interprocess Communication",
  1926.       and contains numerous    unbundled modules numerous networking
  1927.       modules, Chat    and Expect operations, CGI programming,    DCE,
  1928.       FTP, IPC, NNTP, Proxy, Ptty, RPC, SNMP, SMTP,    Telnet,
  1929.       Threads, and ToolTalk--just to name a    few.
  1930.  
  1931.  
  1932.  
  1933.  
  1934.  
  1935.  
  1936.  
  1937.  
  1938.  
  1939.  
  1940.  
  1941.  
  1942.  
  1943.  
  1944.  
  1945.  
  1946.  
  1947.  
  1948.  
  1949.  
  1950.  
  1951.  
  1952.  
  1953.  
  1954.  
  1955.  
  1956.  
  1957.  
  1958.  
  1959.  
  1960.  
  1961.  
  1962.  
  1963.  
  1964.  
  1965.  
  1966.  
  1967.  
  1968.  
  1969.  
  1970.  
  1971.  
  1972.  
  1973.  
  1974.  
  1975.  
  1976.  
  1977.      Page 30                        (printed 10/23/98)
  1978.  
  1979.  
  1980.  
  1981.